package com.lz.sports.ui.config

import android.os.Bundle
import androidx.lifecycle.lifecycleScope
import androidx.navigation.NavController
import androidx.navigation.findNavController
import com.lz.comm.BR
import com.lz.library.base.BaseActivity
import com.lz.library.extension.click
import com.lz.sports.R
import com.lz.sports.databinding.ActDeviceManagerBinding
import com.lz.sports.vm.config.DeviceManagerViewModel
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch

//设备管理
class DeviceManagerActivity : BaseActivity<DeviceManagerViewModel, ActDeviceManagerBinding>() {

    lateinit var navController: NavController

    override fun getLayoutRes(): Int = R.layout.act_device_manager

    override fun getVMVariableId(): Int = BR.vm

    override fun initData(savedState: Bundle?) {
        navController = findNavController(R.id.nav_device)
        lifecycleScope.launch {
            binding.ivBack.click().collect {
                if (!navController.popBackStack()) finish()
            }
        }
        navController.addOnDestinationChangedListener {_, destination, _ ->
            viewModel.label.value = destination.label
            viewModel.showMenu.value = destination.id == R.id.frag_edit
        }

        lifecycleScope.launch {
            binding.tvDelete.click().collect {
                val fragment = supportFragmentManager.findFragmentById(R.id.nav_device)
                    ?.childFragmentManager?.findFragmentByTag("${R.id.frag_edit}")
                if (fragment is MenuDelete && fragment.isResumed) {
                    fragment.delete()
                }
            }
        }
    }
}